import Cancel, { isCancel } from './cancel/Cancel'
import CancelToken from './cancel/CancelToken'
import Axios from './core/Axios'
import mergeConfig from './core/mergeConfig'
import defaults from './default'
import { extend } from './helpers/util'
import {
  // AxiosInstance,
  AxiosRequestConfig,
  AxiosStatic
} from './types'

// 封装工厂函数
function createInstance(config: AxiosRequestConfig): AxiosStatic {
  const context = new Axios(config)
  // instance 就是 Axios 原型上的 request
  const instance = Axios.prototype.request.bind(context)

  // 把 Axios 类原型上的方法扩展到 instance，
  // 实现 axios(config), axios.get(url, config)...
  extend(instance, context)

  return instance as AxiosStatic
}
// 创建 axios 的时候，添加 defaults 默认配置，并扩展到 axios 中
const axios = createInstance(defaults)

axios.create = function create(config) {
  config = mergeConfig(defaults, config)
  return createInstance(config)
}

axios.CancelToken = CancelToken
axios.Cancel = Cancel
axios.isCancel = isCancel

axios.all = function all(promises) {
  return Promise.all(promises)
}

axios.spread = function spread(callback) {
  return function wrap(arr) {
    return callback.apply(null, arr)
  }
}

axios.Axios = Axios

export default axios
